<template>
  <div class="print-box">
    <order ref="order" :dataList="orderPrintDataList"></order>
    <ingredient ref="ingredient" :dataList="ingredientDataList"></ingredient>
  </div>
</template>

<script>
import order from "./order";
import ingredient from "./ingredient";
import { orderTeaPrinting, orderTeaTicketPrinting, orderTeaPrintingFrequency } from "@/api/scheduling/prodManage";
import { query } from "@/api/user"; // 查询生产打印机设备
import { printingDisabledCtrl } from '@/util/print'

export default {
  data() {
    return {
      orderPrintDataList: [],
      ingredientDataList: [],
      printerList: []
    };
  },
  methods: {
    async checkPrinter(indexs) {
      let indexPrinter = this.printerList.filter((item, index) => {
        return indexs.includes(index);
      });
      if (indexPrinter.length > 0) {
        return true;
      } else {
        await this.queryPrinter() // 重新查询一次
        indexPrinter = this.printerList.filter((item, index) => {
          return indexs.includes(index);
        });
        if (indexPrinter.length > 0) {
          return true;
        }
        return false
      }
    },
    // 打印
    async print({ orderList, isNeedIngredient, isOpenPrintPreview }) {
      try {
        printingDisabledCtrl(true)
        const printerValid = await this.checkPrinter([2, 3]);
        if (!printerValid) {
          throw new Error("请到系统模块中的打印机设置中添加打印机");
        }
        this.initPrintData();
        if (orderList && orderList.length) {
          const res1 = await orderTeaTicketPrinting(orderList.map(item => item.id))
          if (res1.data.code === 200 && res1.data.data && res1.data.data.length) {
            this.orderPrintDataList = res1.data.data || []
            this.sameGoodsMerge(this.orderPrintDataList)
            await this.getLoadPromise(1000); // 等待元素渲染
            await this.$refs.order.print(isOpenPrintPreview, this.printerList[2]);
          }
        }
        if (isNeedIngredient) {
          let orderDetailIdList = [];
          orderList.forEach(item => {
            if (item.orderDetailVOS) {
              item.orderDetailVOS.forEach($0 => {
                orderDetailIdList = [
                  ...orderDetailIdList,
                  ...$0.orderDetailIdList
                ];
              });
            }
          });
          const res2 = await orderTeaPrinting(orderDetailIdList);
          if (res2.data.code === 200) {
            const list = res2.data.data || [];
            this.ingredientDataList = list.map(item => {
              return {
                ...item.goodsSkuProductions[0],
                itemData: item
              }
            });
            await this.getLoadPromise(1000); // 等待元素渲染
            await this.$refs.ingredient.print(
              isOpenPrintPreview,
              this.printerList[3]
            );
          }
        }
        this.$notify({
          title: '打印成功',
          message: '请您耐心等待',
          type: 'success'
        })
        orderTeaPrintingFrequency(orderList.map(item => item.id)).then(res => {
          console.log(res)
        })
        this.$emit('printed')
        printingDisabledCtrl(false)
        return true
      } catch (error) {
        console.error(error);
        this.$message.warning(
          error.message ||
            "打印失败，请检查是否安装好驱动和已经连接打印机，或重新打印！"
        );
        printingDisabledCtrl(false)
        return false;
      }
    },
    // 打印小票
    async printOrder({ orderList, isOpenPrintPreview }) {
      try {
        printingDisabledCtrl(true)
        const printerValid = await this.checkPrinter([2]);
        if (!printerValid) {
          throw new Error("请到系统模块中的打印机设置中添加打印机");
        }
        this.initPrintData();
        if (orderList && orderList.length) {
          const res1 = await orderTeaTicketPrinting(orderList.map(item => item.id))
          if (res1.data.code === 200 && res1.data.data && res1.data.data.length) {
            this.orderPrintDataList = res1.data.data || []
            this.sameGoodsMerge(this.orderPrintDataList)
            await this.getLoadPromise(1000); // 等待元素渲染
            await this.$refs.order.print(isOpenPrintPreview, this.printerList[2]);
          }
        }
        this.$notify({
          title: '打印成功',
          message: '请您耐心等待',
          type: 'success'
        })
        printingDisabledCtrl(false)
        return true
      } catch (error) {
        console.error(error);
        this.$message.warning(
          error.message ||
            "打印失败，请检查是否安装好驱动和已经连接打印机，或重新打印！"
        );
        printingDisabledCtrl(false)
        return false;
      }
    },
    // 打印配料表
    async printIngredient({ orderList, isOpenPrintPreview }) {
      try {
        printingDisabledCtrl(true)
        const printerValid = await this.checkPrinter([3]);
        if (!printerValid) {
          throw new Error("请到系统模块中的打印机设置中添加打印机");
        }
        this.initPrintData();
        let orderDetailIdList = [];
        orderList.forEach(item => {
          if (item.orderDetailVOS) {
            item.orderDetailVOS.forEach($0 => {
              orderDetailIdList = [
                ...orderDetailIdList,
                ...$0.orderDetailIdList
              ];
            });
          }
        });
        const res2 = await orderTeaPrinting(orderDetailIdList);
        if (res2.data.code === 200) {
          const list = res2.data.data || [];
          this.ingredientDataList = list.map(item => {
            return {
              ...item.goodsSkuProductions[0],
              itemData: item
            }
          });
          await this.getLoadPromise(1000);
          await this.$refs.ingredient.print(
            isOpenPrintPreview,
            this.printerList[3]
          );
        }
        this.$notify({
          title: '打印成功',
          message: '请您耐心等待',
          type: 'success'
        })
        printingDisabledCtrl(false)
        return true
      } catch (error) {
        console.error(error);
        this.$message.warning(
          error.message ||
            "打印失败，请检查是否安装好驱动和已经连接打印机，或重新打印！"
        );
        printingDisabledCtrl(false)
        return false;
      }
    },
    getLoadPromise(time) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve();
        }, time || 1000);
      });
    },
    initPrintData() {
      this.orderPrintDataList = [];
      this.ingredientDataList = [];
    },
    // 查询打印机
    queryPrinter() {
      let params = {
        type: 1,
        key: "[1,2]",
        userId: JSON.parse(window.localStorage.getItem("saber-userInfo"))
          .content.account
      };
      return query(params).then(res => {
        if (res.data.code === 0 && res.data.data[0]) {
          this.printerList = JSON.parse(res.data.data[0].value) || [];
        }
      });
    },
    // 将订单相同的商品合并
    sameGoodsMerge(orderList) {
      orderList.forEach(itemorder => {
        if (itemorder.orderDetail && itemorder.orderDetail.length) {
          const goods = []
          itemorder.orderDetail.forEach(item => {
            const findGood = goods.find(g => item.goodsId === g.goodsId)
            if (findGood) {
              findGood.quantity++
              findGood.orderDetailIdList.push(item.id)
            } else {
              item.quantity = 1
              item.orderDetailIdList = [item.id]
              goods.push(item)
            }
          })
          itemorder.orderDetail = goods
        }
      });
    },
  },
  created() {
    this.queryPrinter()
  },
  components: {
    order,
    ingredient
  }
};
</script>
<style lang="scss" scoped>
.print-box {
  z-index: -1;
  position: fixed;
  bottom: -1000%;
  right: -1000%;
}
</style>
